package com.jiyi.view;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.activity.zone.PersonInfoActivity;
import com.jiyi.activity.zone.ZoneHuoDongMemberActivity;
import com.jiyi.bean.zone.HuoDongDetailJson.HuoDongDetail;
import com.jiyi.bean.zone.ZoneHaoYouBean;
import com.jiyi.bean.zone.ZoneHuoDongBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.event.HuoDongListEvent;
import com.jiyi.event.HuoDongStatuEvent;
import com.jiyi.inteface.HuoDongPopInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.VerticalTextView;
import com.swift.base.ApplicationBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.maintenance.utils.ZoneHuoDongUtil;
import com.swift.utils.DeviceUtil;
import com.swift.utils.GlideUtil;
import com.swift.widget.CircleImageView;

public class HuoDongPopView {

	private HuoDongPopInterface mHuoDongPopInterface;
	private Context context;
	private PopupWindow mPopupWindow;
	// private ZoneHuoDongBean zoneHuoDongBean;
	private HuoDongDetail huoDongDetail;

	VerticalTextView tvJoinNum;
	ImageView huoDongLogo;
	TextView tvHuoDongName;
	ImageView creatorLogo;
	TextView creatorName;
	TextView createDate;
	TextView tvHuoDongJianJie;
	TextView tvStartDate;
	TextView tvAddress;
	LinearLayout llJoinMember;
	ImageView ivNext;
	ImageView ivHuoDongMore;
	TextView tvExit;
	VerticalTextView tvJoinMember;
	TextView tvState;
	RelativeLayout rlTip;
	TextView tvTip;
	TextView tvGoTo;
	ProgressBar progressBar;

	// 加入成功提示
	private String joinSuccess = "您的申请已发送，已加入该活动";
	// 退出成功提示
	private String exitSuccess = "您的申请已发送，已退出该活动";

	public HuoDongPopView(Context context,
			HuoDongPopInterface huoDongPopInterface) {
		this.context = context;
		this.mHuoDongPopInterface = huoDongPopInterface;
		init();
	}

	/**
	 * @author: HYM
	 * @Title: init
	 * @Description: TODO(初始化一个新的PopWindow)
	 * @param:
	 * @return: void
	 * @return: 2017-5-5
	 * @throws
	 */
	private void init() {
		// 得到内容布局
		View view = LayoutInflater.from(context).inflate(R.layout.pop_huodong,
				null);

		// 取消按钮
		ImageView ivClose = (ImageView) view.findViewById(R.id.ivClose);
		ivClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mHuoDongPopInterface.OnCancleListener();
				hidePopWindow();
			}
		});

		// 确定按钮
		tvState = (TextView) view.findViewById(R.id.tvState);

		// 发起人头像
		creatorLogo = (ImageView) view.findViewById(R.id.creatorLogo);
		// 参加人数
		tvJoinNum = (VerticalTextView) view.findViewById(R.id.tvJoinNum);
		// 活动Logo
		huoDongLogo = (ImageView) view.findViewById(R.id.huoDongLogo);
		// 活动名称
		tvHuoDongName = (TextView) view.findViewById(R.id.tvHuoDongName);
		// 发起人名称
		creatorName = (TextView) view.findViewById(R.id.creatorName);
		// 活动创建时间
		createDate = (TextView) view.findViewById(R.id.createDate);
		// 活动简介
		tvHuoDongJianJie = (TextView) view.findViewById(R.id.tvHuoDongJianJie);
		// 活动开始时间
		tvStartDate = (TextView) view.findViewById(R.id.tvStartDate);
		// 活动地址
		tvAddress = (TextView) view.findViewById(R.id.tvAddress);
		// 活动参与者
		llJoinMember = (LinearLayout) view.findViewById(R.id.llJoinMember);
		// 更多参与者
		ivNext = (ImageView) view.findViewById(R.id.ivNext);
		// 参与者
		tvJoinMember = (VerticalTextView) view.findViewById(R.id.tvJoinMember);
		// 更多设置
		ivHuoDongMore = (ImageView) view.findViewById(R.id.ivHuoDongMore);
		// 退出按钮
		tvExit = (TextView) view.findViewById(R.id.tvExit);
		// 底部提示信息
		rlTip = (RelativeLayout) view.findViewById(R.id.rlTip);
		rlTip.setVisibility(View.GONE);
		tvTip = (TextView) view.findViewById(R.id.tvTip);
		tvGoTo = (TextView) view.findViewById(R.id.tvGoTo);
		progressBar = (ProgressBar) view.findViewById(R.id.progressBar);

		mPopupWindow = new PopupWindow(view,
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		mPopupWindow.setFocusable(true); // 让popWindow获取焦点
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable()); // 设置popWindow背景颜色
		mPopupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
		mPopupWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				hidePopWindow();
			}
		});
	}

	/**
	 * @author: HYM
	 * @Title: showPopWindow
	 * @Description: TODO(显示弹出菜单)
	 * @param:
	 * @return: void
	 * @return: 2017-4-26
	 * @throws
	 */
	public void showPopWindow(final HuoDongDetail huoDongDetail) {

		initView();

		if (null != huoDongDetail) {
			// setZoneHuoDongBean(zoneHuoDongBean);
			setHuoDongDetail(huoDongDetail);
			final ZoneHuoDongBean zoneHuoDongBean = huoDongDetail.getActInfo();
			// final ZoneHaoYouBean zoneHaoYouBean =
			// huoDongDetail.getUserList();

			tvJoinNum.setText(zoneHuoDongBean.getAttendPer() + "人参与");
			GlideUtil.load(huoDongLogo.getContext(),
					zoneHuoDongBean.getCover(), huoDongLogo);
			tvHuoDongName.setText(zoneHuoDongBean.getTheme());
			GlideUtil.load(creatorLogo.getContext(),
					zoneHuoDongBean.getHead_path(), creatorLogo);
			creatorLogo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(v.getContext(),
							PersonInfoActivity.class);
					intent.putExtra("id", zoneHuoDongBean.getUser_id());
					v.getContext().startActivity(intent);
				}
			});
			creatorName.setText(zoneHuoDongBean.getName());
			createDate.setText(zoneHuoDongBean.getCreate_time());
			tvStartDate.setText(zoneHuoDongBean.getStart_time() + " 至 "
					+ zoneHuoDongBean.getEnd_time());
			tvAddress.setText(zoneHuoDongBean.getAddress());
			// tvState.setText(ZoneHelper.getStatu(
			// Integer.parseInt(zoneHuoDongBean.getStatus()), isJoin()));
			// 1.等待报名,2.用户可参与，3.等待开始，4.进行中，5.活动结束，6.活动取消
			int status = zoneHuoDongBean.getFlag();
			ZoneHuoDongUtil.setStatus(tvState, status);

			if (status == 2) {
				tvState.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						tvState.setVisibility(View.GONE);
						joinHuoDong(huoDongDetail.getActInfo().getId());
					}
				});
			}
			else {
				tvState.setOnClickListener(null);
			}

			tvHuoDongJianJie.setText(zoneHuoDongBean.getIntroduction());

			setMember(huoDongDetail.getUserList());
			llJoinMember.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					List<ZoneHaoYouBean> datas = huoDongDetail.getUserList();
					Intent intent = new Intent(ivNext.getContext(),
							ZoneHuoDongMemberActivity.class);
					intent.putExtra("max", zoneHuoDongBean.getMax_user_num());
					intent.putExtra("user", new Gson().toJson(datas));
					v.getContext().startActivity(intent);
				}
			});
			ivNext.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					List<ZoneHaoYouBean> datas = huoDongDetail.getUserList();
					Intent intent = new Intent(ivNext.getContext(),
							ZoneHuoDongMemberActivity.class);
					intent.putExtra("max", zoneHuoDongBean.getMax_user_num());
					intent.putExtra("user", new Gson().toJson(datas));
					v.getContext().startActivity(intent);
				}
			});

			//判断是否是创建人
			if (UserInfoUtil.getCurrentUserId() == Integer.parseInt(zoneHuoDongBean.getUser_id())) {
				tvExit.setText("取消活动");
			}
			else {
				tvExit.setText("退出活动");
			}
			
			ivHuoDongMore.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (tvExit.getVisibility() == View.VISIBLE) {
						tvExit.setVisibility(View.GONE);
					} else {
						tvExit.setVisibility(View.VISIBLE);
					}
				}
			});

			tvExit.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 退出活动接口
					exitHuoDong(huoDongDetail.getActInfo().getId());
				}
			});

			if (isShowMore()) {
				ivHuoDongMore.setVisibility(View.VISIBLE);
			} else {
				ivHuoDongMore.setVisibility(View.GONE);
			}

			// 初始化底部的按钮与提示
			rlTip.setVisibility(View.GONE);
			tvTip.setText("");
			tvState.setVisibility(View.VISIBLE);
		}
		mPopupWindow
				.showAtLocation(new TextView(context), Gravity.CENTER, 0, 0);
		backgroundAlpha(0.5F);
		mHuoDongPopInterface.OnShowListener();
	}

	/**
	 * @author: HYM
	 * @Title: hidePopWindow
	 * @Description: TODO(关闭弹出菜单)
	 * @param:
	 * @return: void
	 * @return: 2017-4-26
	 * @throws
	 */
	public void hidePopWindow() {
		// 隐藏退出按钮
		if (tvExit.getVisibility() == View.VISIBLE) {
			tvExit.setVisibility(View.GONE);
		}

		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		}
		backgroundAlpha(1F);
		mHuoDongPopInterface.OnHideListener();
	}

	/**
	 * 设置添加屏幕的背景透明度
	 * 
	 * @param bgAlpha
	 */
	public void backgroundAlpha(float bgAlpha) {
		Activity activity = (Activity) context;
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.alpha = bgAlpha; // 0.0-1.0
		activity.getWindow().setAttributes(lp);
		activity.getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_DIM_BEHIND);
	}

	// public ZoneHuoDongBean getZoneHuoDongBean() {
	// return zoneHuoDongBean;
	// }
	//
	// public void setZoneHuoDongBean(ZoneHuoDongBean zoneHuoDongBean) {
	// this.zoneHuoDongBean = zoneHuoDongBean;
	// }

	/**
	 * @author: HYM
	 * @Title: setMember
	 * @Description: TODO(设置参与者) void
	 * @date: 2017-6-19
	 */
	private void setMember(List<ZoneHaoYouBean> haoYouDatas) {
		// 得到像素密度
		float density = DeviceUtil.getInstance().getBiLi(); // 像素密度
		// 获取屏幕的宽度
		int screenWidth = DeviceUtil.getInstance().getScreenWidth();
		// 减去左右两边的padding各10
		screenWidth -= 20 * density;
		tvJoinMember.measure(0, 0);
		ivNext.measure(0, 0);
		// 得到参与者文本的宽度
		int aw = tvJoinMember.getMeasuredWidth();
		// 得到更多图标的宽度
		int bw = ivNext.getMeasuredWidth();
		// 当前的可显示头像宽度 = 总的屏幕宽度-（参与者的宽度+自身的左右padding） - （更多图标的宽度+margin = 10）
		screenWidth = (int) (screenWidth - aw - bw
				- tvJoinMember.getPaddingLeft()
				- tvJoinMember.getPaddingRight() - 10 * density);
		final int width = screenWidth;
		Log.d("width  ", width + "");
		// 求出最大可放的头像个数
		int maxNum = (int) Math.floor(width / (40 * density + 20 * density));
		if (maxNum > 0) {

			// 判断当前成员与最大可显示成员的关系,成员数量如果小于最大数量时，就只显示成员数量
			if (maxNum >= haoYouDatas.size()) {
				maxNum = haoYouDatas.size();
			}

			this.llJoinMember.removeAllViews();
			for (int i = 0; i < maxNum; i++) {
				this.llJoinMember.addView(getCircleImageView(haoYouDatas.get(i)
						.getHead_path(), this.llJoinMember));
			}
		}
	}

	public HuoDongDetail getHuoDongDetail() {
		return huoDongDetail;
	}

	public void setHuoDongDetail(HuoDongDetail huoDongDetail) {
		this.huoDongDetail = huoDongDetail;
	}

	private CircleImageView getCircleImageView(String headurl, final View parent) {
		float bili = DeviceUtil.getInstance().getBiLi();

		CircleImageView circleImageView = new CircleImageView(
				parent.getContext());
		// circleImageView.setImageResource(R.drawable.ic_launcher);
		GlideUtil.load(parent.getContext(), headurl, circleImageView);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				(int) (40 * bili), (int) (40 * bili));
		params.setMargins(0, 0, (int) (20 * bili), 0);
		circleImageView.setLayoutParams(params);
		return circleImageView;
	}

	/**
	 * @author: HYM
	 * @Title: isShowMore
	 * @Description: TODO(是否显示更多按钮)
	 * @return boolean
	 * @date: 2017-7-17
	 */
	boolean isShowMore() {
		// 进行中前才可以退出活动
		if (huoDongDetail.getActInfo().getFlag() < 4
				&& isJoin()) {
			return true;
		}
		return false;
	}

	/**
	 * @author: HYM
	 * @Title: isJoin
	 * @Description: TODO(是否参与其中)
	 * @return boolean
	 * @date: 2017-7-17
	 */
	boolean isJoin() {
		for (int i = 0; i < huoDongDetail.getUserList().size(); i++) {
			if (Integer.parseInt(huoDongDetail.getUserList().get(i).getId()) == UserInfoUtil
					.getCurrentUserId()) {
				return true;
			}
		}
		return false;
	}

	void exitHuoDong(final String id) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);

		VolleyRequest.StringRequestPost(context, WebApi.ZONE_HUODONG_EXIT, "",
				params, new StringInterface(context) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								EventBus.getDefault().post(
										new HuoDongStatuEvent(2, id));
								EventBus.getDefault().postSticky(new HuoDongListEvent(HuoDongListEvent.MY_HUODONG_FRAGMENT));
								EventBus.getDefault().postSticky(new HuoDongListEvent(HuoDongListEvent.ALL_HUODONG_FRAGMENT));
								hidePopWindow();
								ToastUtil.getInstances().showMsg("退出成功");
								// ivHuoDongMore.setVisibility(View.GONE);
								// tvExit.setVisibility(View.GONE);
								// tvState.setVisibility(View.GONE);
								// rlTip.setVisibility(View.VISIBLE);
								// tvTip.setText(exitSuccess);

							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}

	void joinHuoDong(final String id) {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);

		progressBar.setVisibility(View.VISIBLE);
		VolleyRequest.StringRequestPost(context, WebApi.ZONE_HUODONG_JOIN, "",
				params, new StringInterface(context) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								EventBus.getDefault().post(
										new HuoDongStatuEvent(3, id));
								EventBus.getDefault()
										.postSticky(
												new HuoDongListEvent(
														HuoDongListEvent.MY_HUODONG_FRAGMENT));
								hidePopWindow();
								ToastUtil.getInstances().showMsg("加入成功");
								// tvState.setVisibility(View.GONE);
								// rlTip.setVisibility(View.VISIBLE);
								// tvTip.setText(joinSuccess);

								// mHuoDongPopInterface.OnSureListener();
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							progressBar.setVisibility(View.GONE);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						tvState.setVisibility(View.VISIBLE);
						progressBar.setVisibility(View.GONE);
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}

	/**
	 * @author: HYM
	 * @Title: initView
	 * @Description: TODO(因为POP是一次性加载的，所以每次进来时，需要复位下底部提示状态) void
	 * @date: 2017-7-21
	 */
	void initView() {
		tvState.setVisibility(View.VISIBLE);
		rlTip.setVisibility(View.GONE);
	}
}
